﻿using Microsoft.AspNetCore.Mvc;
using ModelBinder.Extension.AspNetCore.FromSmartBody;
using System.Linq.Expressions;
using VueShopApi.Common;
using VueShopApi.Entities;

namespace VueShopApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrdersController : AuthorizeController
    {
        private readonly ILogger<OrdersController> _logger;
        private readonly IFreeSql _context;

        public OrdersController(ILogger<OrdersController> logger, IFreeSql context)
        {
            _logger = logger;
            _context = context;
        }

        [HttpGet]
        public async Task<IActionResult> GetAllOrders(string query, [FromSmartBody("is_send")] int? userId,
            [FromSmartBody("pay_status")] int? payStatus, [FromSmartBody("is_send")] int? isSend, [FromSmartBody("order_fapiao_title")] int? title,
            [FromSmartBody("order_fapiao_company")] string company, [FromSmartBody("order_fapiao_content")] string content, [FromSmartBody("consignee_addr")] string address, int pagenum = 1, int pagesize = 10)
        {
            Expression<Func<SpOrder, bool>> expression = g => true;

            if (userId.HasValue)
            {
                expression = expression.And(g => g.UserId == userId.Value);
            }

            if (payStatus.HasValue)
            {
                expression = expression.And(g => g.PayStatus == payStatus.Value);
            }

            if (isSend.HasValue)
            {
                expression = expression.And(g => g.IsSend == (isSend.Value == 1 ? "是" : "否"));
            }

            if (title.HasValue)
            {
                expression = expression.And(g => g.OrderFapiaoTitle == (title.Value == 1 ? "个人" : "公司"));
            }

            if (string.IsNullOrWhiteSpace(company))
            {
                expression = expression.And(g => g.OrderFapiaoCompany.Contains(company));
            }

            if (string.IsNullOrWhiteSpace(content))
            {
                expression = expression.And(g => g.OrderFapiaoContent.Contains(content));
            }

            if (string.IsNullOrWhiteSpace(address))
            {
                expression = expression.And(g => g.ConsigneeAddr.Contains(address));
            }

            var goods = await _context.Select<SpOrder>()
                .Where(expression)
                .OrderByDescending(o => o.CreateTime)
                .Count(out var total)
                .Page(pagenum, pagesize).ToListAsync();

            return ServerResponse.Yes(new
            {
                total,
                pagenum,
                pagesize,
                goods
            });
        }


    }
}
